use actix_web::{Error, get};
use excelwriter::*;
use uuid::Uuid;
use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionType,DispositionParam};
#[get("/test/exportexcel")]
pub async fn exportexcel()  ->  Result<fs::NamedFile, Error> {

    match std::fs::create_dir("/tmp") {
        Err(why) => println!("! {:?}", why.kind()),
        Ok(_) => {},
    }
    let filename:String =format!("/tmp/{}.xlsx",Uuid::new_v4() ) ;
    let mut wb = Workbook::create(&filename);
    let mut sheet = wb.create_sheet("第一页");

    // set column width
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 80.0 });
    sheet.add_column(Column { width: 60.0 });

    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","XML Remark"])?;
        sw.append_row(row!["Amy", (), true,"<xml><tag>\"Hello\" & 'World'</tag></xml>"])?;
        sw.append_blank_rows(2);
        sw.append_row(row!["Tony", blank!(2), "retired"])
    }).expect("write excel error!");

    let mut sheet = wb.create_sheet("第二页");
    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","Remark"])?;
        sw.append_row(row!["Amy", "Manager", true])
    }).expect("write excel error!");

    
    wb.close().expect("close excel error!");
   
    let file = fs::NamedFile::open(filename)?;
    Ok(file
        .use_last_modified(true)
        .set_content_type( "application/vnd.ms-excel;charset=utf-8".parse().unwrap() )
        .set_content_disposition(ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![DispositionParam::Filename(String::from("导出excel文件.xlsx"))],
        }))
    
}
